<template>
  <div class="app-container">
    <el-card>
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="设备型号">
          <el-input
            v-model="queryParams.deviceModel"
            placeholder="请输入设备型号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备序列号">
          <el-input
            v-model="queryParams.imei"
            placeholder="请输入设备序列号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="设备类型">
          <el-select
            v-model="queryParams.typeId"
            clearable
            placeholder="请选择设备类型"
            style="width: 240px"
          >
            <el-option
              v-for="dict in deviceList"
              :key="dict.id"
              :label="dict.typeName"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="adddeviceRegistration"
            >新增</el-button
          >
          <el-button icon="Upload" plain type="success" @click="handleImport"
            >导入
          </el-button>
        </el-col>

        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="postList"
        stripe
        border
        max-height="500"
      >
        <el-table-column
          label="设备序列号"
          align="center"
          prop="imei"
          width="200"
        />
        <el-table-column
          label="设备型号"
          align="center"
          prop="deviceModel"
          width="200"
        />
        <el-table-column label="设备类型" align="center" prop="typeName" />
        <el-table-column label="联网类型" align="center" width="100">
          <template #default="scope">
            <span>
              {{
                network_type.find((item) => item.value == scope.row.networkType)
                  ? network_type.find(
                      (item) => item.value == scope.row.networkType
                    ).label
                  : ""
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="网关设备序列号"
          align="center"
          prop="gatewayDeviceTypeName"
        />
        <el-table-column label="注册时间" align="center" prop="createTime" />
        <el-table-column label="备注" align="center" prop="notes" />
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      v-model="open"
      :title="title"
      append-to-body
      width="600px"
      v-if="open"
      @close="cancel"
      :close-on-click-modal="false"
    >
      <el-form
        ref="deviceRegistrationRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="设备型号" prop="modelId">
          <el-select
            v-model="form.modelId"
            clearable
            placeholder="请选择设备型号"
            style="width: 100%"
          >
            <el-option
              v-for="dict in wayList"
              :key="dict.id"
              :label="dict.deviceModel"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备序列号" prop="imei">
          <el-input v-model="form.imei" placeholder="请输入设备序列号" />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="form.notes"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 8 }"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormDebounceHandler"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改岗位对话框 -->
    <el-dialog
      v-model="upload.open"
      :title="upload.title"
      append-to-body
      width="400px"
    >
      <el-upload
        ref="uploaddeviceregRef"
        :action="upload.url"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              type="primary"
              @click="importTemplate"
              >下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="deviceRegistration">
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex, network_type } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex",
  "network_type"
);
import {
  devicetypeList,
  deviceregList,
  deviceregDel,
  devicemodelList,
  updatedevicereg,
  adddevicereg,
} from "@/api/equipment/index";
import { debounce } from "@/utils/debounce.js";
import batter from "./BatteryDisplay.vue";
const showSearch = ref(true);
const loading = ref(true);
const postList = ref([]);
const open = ref(false);
const title = ref("新增设备注册");
const deviceList = ref([]);
import { getToken } from "@/utils/auth";
const wayList = ref([]);

const total = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    limit: 10,
    deviceModel: undefined,
    imei: undefined,
    typeId: undefined,
  },
  rules: {
    modelId: [{ required: true, message: "请选择设备型号", trigger: "change" }],
    imei: [
      { required: true, message: "请输入设备序列号", trigger: "blur" },
      { min: 1, max: 32, message: "设备序列号长度不能超过32", trigger: "blur" },
    ],
    notes: [
      {
        required: false,
        min: 0,
        max: 500,
        message: "备注不能超过500",
        trigger: "blur",
      },
    ],
  },
});
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: process.env.VUE_APP_BASE_API + "/pk-iot/iot/devicereg/importData",
});

const { queryParams, form, rules } = toRefs(data);

/** 查询岗位列表 */
function getList() {
  loading.value = true;
  deviceregList(queryParams.value).then((response) => {
    postList.value = response.page.list;
    total.value = response.page.totalCount;
    loading.value = false;
  });
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploaddeviceregRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploaddeviceregRef"].submit();
}
function importTemplate() {
  proxy.download(
    "pk-iot/iot/devicereg/export",
    {},
    `devicereg_template_${new Date().getTime()}.xlsx`
  );
}

function handleImport() {
  upload.title = "设备注册导入";
  upload.open = true;
}

const submitFormDebounceHandler = debounce(submitForm, 500);

function submitForm() {
  proxy.$refs["deviceRegistrationRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updatedevicereg(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          reset();
          getList();
        });
      } else {
        adddevicereg(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          reset();
          getList();
        });
      }
    }
  });
}
function handleEdit(data) {
  form.value.id = data.id;
  form.value.modelId = data.modelId;
  form.value.imei = data.imei;
  form.value.notes = data.notes;
  title.value = "编辑设备注册";
  open.value = true;
}
function cancel() {
  open.value = false;
  reset();
}
function reset() {
  form.value = {
    id: null,
    modelId: undefined,
    imei: undefined,
    notes: undefined,
  };
  proxy.resetForm("deviceRegistrationRef");
}
function adddeviceRegistration() {
  title.value = "新增设备注册";
  open.value = true;
}
function handleDelete(row) {
  proxy.$modal
    .confirm("是否确认删除该数据项？")
    .then(function () {
      return deviceregDel([row.id]);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
function getGateway() {
  let obj = {
    page: 1,
    limit: 999,
  };
  devicemodelList(obj).then((res) => {
    console.log("res", res);
    wayList.value = res.page.list;
  });
}
function getdevicetypeList() {
  let obj = {
    page: 1,
    limit: 999,
  };
  devicetypeList(obj).then((res) => {
    console.log("22222", res);
    deviceList.value = res.page.list;
  });
}
function handleQuery() {
  getList();
}
function resetQuery() {
  queryParams.value = {
    page: 1,
    limit: 10,
    deviceModel: undefined,
    imei: undefined,
    typeId: undefined,
  };
  getList();
}
getList();
getdevicetypeList();
getGateway();
</script>
